package com.rmfyzxfw.caseprocess.config;

import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Configuration
public class LocalDateTimeSerializerConfig {


    private static String yyyyMMddHHmmss;
    private static String yyyyMMdd = "yyyy-MM-dd";

    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private void setPattern(String pattern) {
        yyyyMMddHHmmss = pattern;
    }

    @Bean
    public LocalDateTimeSerializer localDateTimeSerializer() {
        return new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(yyyyMMddHHmmss));
    }


    @Bean
    public LocalDateTimeDeserializer localDateTimeDeserializer() {
        return new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(yyyyMMddHHmmss));
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder
                .serializerByType(LocalDateTime.class, localDateTimeSerializer())
                .deserializerByType(LocalDateTime.class, localDateTimeDeserializer());
    }

    @Bean
    public Converter<String, LocalDateTime> string2LocalDateTimeConverter() {
        return new String2LocalDateTimeConverter();
    }

    public static class String2LocalDateTimeConverter implements Converter<String, LocalDateTime> {
        @Override
        public LocalDateTime convert(String s) {
            return LocalDateTime.parse(s, DateTimeFormatter.ofPattern(yyyyMMddHHmmss));
        }
    }

    @Bean
    public Converter<LocalDateTime, String> localDateTime2StringConverter() {
        return new LocalDateTime2StringConverter();
    }

    public static class LocalDateTime2StringConverter implements Converter<LocalDateTime, String> {
        @Override
        public String convert(LocalDateTime localDateTime) {
            return localDateTime.format(DateTimeFormatter.ofPattern(yyyyMMddHHmmss));
        }
    }

    @Bean
    public Converter<String, LocalDate> string2LocalDateConverter() {
        return new String2LocalDateConverter();
    }

    public static class String2LocalDateConverter implements Converter<String, LocalDate> {
        @Override
        public LocalDate convert(String s) {
            return LocalDate.parse(s, DateTimeFormatter.ofPattern(yyyyMMdd));
        }
    }

}
